﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using AvalonDock;
using RiskMan.Config;
using RiskMan.DataClass.Models;
using System.Windows.Threading;
using System.Collections.ObjectModel;
using RiskMan.DataClass.Models.RM;
using RiskMan.Views.Dialogs;
using System.Reflection;

namespace RiskMan.Views.RiskManager
{
    public partial class RiskManager : DocumentContent
    {
        private MainWindow mainWindow;
        private DispatcherTimer _dsTimer = new DispatcherTimer( );
        VerificationLicense ver = new VerificationLicense();

        public RiskManager ( )
        {
            mainWindow = RiskMan.MainWindow.StaticRiskMan;

            InitializeComponent( );
            this.Title = cfg.MainfunctionRm;
        }

        public void Terminals_OnTerminalsTransaction ( object error, int tid, double orderId, string msgError )
        {

        }

        #region добавление строки

        private void BtnAddRow_Click ( object sender, RoutedEventArgs e )
        {
            RmItem item = new RmItem( );
            NewRmItem nrmi = new NewRmItem( item, mainWindow._dataProvider, false );
            nrmi.ShowDialog( );

            if ( item.Account != null )
                mainWindow._dataProvider.RMItems.Add( item );

            Update( );
            cfg.SetLog( "Добавлена новая строка риск менеджера", mainWindow.ListBox_Logs, GetType( ), MethodBase.GetCurrentMethod( ) );

        }
        #endregion

        #region обновление контектста у DataGrid

        public void Update ( )
        {
            DtgdRm.CanUserAddRows = true;

            mainWindow._dataProvider.RMItems = this.GetUpdate( mainWindow._dataProvider.RMItems );
            DtgdRm.ItemsSource = mainWindow._dataProvider.RMItems;
            DgtdCurrentCalculation.ItemsSource = mainWindow._dataProvider.ACLimiteItems;
            DtgdRm.CanUserAddRows = false;
        }

        private ObservableCollection<RmItem> GetUpdate ( ObservableCollection<RmItem> observableCollection )
        {
            foreach ( var tmp in observableCollection )
            {
                tmp.AccountList = this.GetAccounts( );
                tmp.ClientCodeList = this.GetClientCodes( );
            }
            return observableCollection;
        }

        private List<string> GetClientCodes ( )
        {
            List<Trade> trades = new List<Trade>( );
            List<String> result = new List<string>( );

            for ( int i = 0; i < mainWindow._dataProvider.T2QItems.Count; i++ )
                for ( int j = 0; j < mainWindow._dataProvider.T2QItems [ i ].TradeList.Count; j++ )
                    trades.Add( mainWindow._dataProvider.T2QItems [ i ].TradeList [ j ] );

            foreach ( var tmp in trades )
            {
                bool tr = false;
                foreach ( var tm in result )
                {
                    if ( tmp.ClientCode == tm )
                        tr = true;
                }
                if ( tr == false )
                    result.Add( tmp.ClientCode );
            }

            return result;
        }

        private List<string> GetAccounts ( )
        {
            List<Trade> trades = new List<Trade>( );
            List<String> result = new List<string>( );

            for ( int i = 0; i < mainWindow._dataProvider.T2QItems.Count; i++ )
                for ( int j = 0; j < mainWindow._dataProvider.T2QItems [ i ].TradeList.Count; j++ )
                    trades.Add( mainWindow._dataProvider.T2QItems [ i ].TradeList [ j ] );

            for ( int i = 0; i < trades.Count; i++ )
            {
                bool tr = false;
                for ( int j = 0; j < result.Count; j++ )
                {
                    if ( trades [ i ].Account == result[j] )
                        tr = true;
                }
                if ( tr == false )
                    result.Add( trades[i].Account );
            }

            return result;
        }

        #endregion

        #region удаление из массива стопа

        private void Button_DeleteItem_Click ( object sender, RoutedEventArgs e )
        {
            for ( int i = 0; i < mainWindow._dataProvider.ACLimiteItems.Count; i++ )
            {
                if ( mainWindow._dataProvider.ACLimiteItems [ i ].Account == mainWindow._dataProvider.RMItems [ DtgdRm.SelectedIndex ].Account &&
                    mainWindow._dataProvider.ACLimiteItems [ i ].ClientCode == mainWindow._dataProvider.RMItems [ DtgdRm.SelectedIndex ].ClientCode )
                    mainWindow._dataProvider.ACLimiteItems.RemoveAt( i );
            }

            mainWindow._dataProvider.RMItems.RemoveAt( DtgdRm.SelectedIndex );
            DtgdRm.ItemsSource = mainWindow._dataProvider.RMItems;
        }

        #endregion

        #region начало выполнения


        private bool IsParam ( string seccode )
        {
            try
            {
                var res = mainWindow._dataProvider.CurrentList.Where( a => a.Seccode == seccode ).ToList( );
                if ( res.Count != 0 )
                    return true;
            }
            catch ( Exception ) { }
            return false;
        }

        #endregion

        private void Account_SelectionChanged ( object sender, SelectionChangedEventArgs e )
        {
            if ( ( ( ComboBox ) sender ).SelectedValue.ToString( ) != cfg.Unknown )
            {
                string selected = ( ( ComboBox ) sender ).SelectedValue.ToString( );

                List<string> clientCode = new List<string>( );
                for ( int i = 0; i < mainWindow._dataProvider.T2QItems.Count; i++ )
                {
                    for ( int j = 0; j < mainWindow._dataProvider.T2QItems [ i ].TradeList.Count; j++ )
                    {
                        if ( mainWindow._dataProvider.T2QItems [ i ].TradeList [ j ].Account == selected )
                        {
                            clientCode.Add( mainWindow._dataProvider.T2QItems [ i ].TradeList [ j ].ClientCode );
                        }
                    }
                }

                mainWindow._dataProvider.RMItems [ DtgdRm.SelectedIndex ].ClientCodeList = clientCode;
                mainWindow._dataProvider.RMItems [ DtgdRm.SelectedIndex ].ClientCode = cfg.Unknown;
            }
        }

        private void DtgdRm_MouseDoubleClick ( object sender, MouseButtonEventArgs e )
        {
            if ( DtgdRm.SelectedIndex >= 0 )
            {
                RmItem rmItem = ( ( DataGrid ) sender ).SelectedItem as RmItem;
                NewRmItem nri = new NewRmItem( rmItem, mainWindow._dataProvider, true );
                nri.ShowDialog( );
            }
        }

        #region Копирование ноастроенной строки риск менеджера

        private void DtgdRm_MouseRightButtonUp ( object sender, MouseButtonEventArgs e )
        {
            if ( ( sender as System.Windows.Controls.DataGrid ).SelectedItems.Count == 1 )
            {
                int index = ( sender as System.Windows.Controls.DataGrid ).SelectedIndex + 1;
                DtgdRm.UnselectAll( );
                if ( new DialogYesNo( "Вы действительно хотите скопировать строку " + index + "?", "Внимаение" ).Result == MessageBoxResult.Yes )
                {
                    var tmp = ( RmItem ) cfg.DeepClone( mainWindow._dataProvider.RMItems [ index - 1 < 0 ? 0 : index - 1 ] );
                    if ( tmp.isRun == false )
                        mainWindow._dataProvider.RMItems.Add( tmp );
                    else
                        new DialogOkCancel( "Для продолжения копирования нужно остановить копируемю строку", "Ошибка" );
                }
            }
        }

        private void BtnCopy_Click ( object sender, RoutedEventArgs e )
        {
            if ( DtgdRm.SelectedItems.Count == 1 )
            {
                int index = DtgdRm.SelectedIndex + 1;
                DtgdRm.UnselectAll( );
                if ( new DialogOkCancel( "Вы действительно хотите скопировать строку " + index + "?", "Внимание" ).Result == MessageBoxResult.OK )
                {
                    var tmp = ( RmItem ) cfg.DeepClone( mainWindow._dataProvider.RMItems [ index - 1 < 0 ? 0 : index - 1 ] );
                    if ( tmp.isRun == false )
                        mainWindow._dataProvider.RMItems.Add( tmp );
                    else
                        new DialogOkCancel( "Для продолжения копирования нужно остановить копируемю строку", "Ошибка" );
                }
            }
        }

        #endregion


        /// <summary>
        /// Удаление 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnStop_Click ( object sender, RoutedEventArgs e )
        {
            for ( int j = 0; j < mainWindow._dataProvider.RMItems.Count; j++ )
            {
                if ( mainWindow._dataProvider.RMItems [ j ].Check == true )
                {
                    for ( int i = 0; i < mainWindow._dataProvider.ACLimiteItems.Count; i++ )
                    {
                        if ( mainWindow._dataProvider.ACLimiteItems [ i ].Account == mainWindow._dataProvider.RMItems [ j ].Account &&
                            mainWindow._dataProvider.ACLimiteItems [ i ].ClientCode == mainWindow._dataProvider.RMItems [ j ].ClientCode )
                            mainWindow._dataProvider.ACLimiteItems.RemoveAt( i );
                    }

                    mainWindow._dataProvider.RMItems.RemoveAt( j );
                    j--;
                }
            }

            DtgdRm.ItemsSource = mainWindow._dataProvider.RMItems;
        }

        private void CheckBox_Click ( object sender, RoutedEventArgs e )
        {
            for ( int i = 0; i < mainWindow._dataProvider.RMItems.Count; i++ )
            {
                mainWindow._dataProvider.RMItems [ i ].Check = ( sender as CheckBox ).IsChecked.Value;
            }
            DtgdRm.ItemsSource = mainWindow._dataProvider.RMItems;
        }

        /// <summary>
        /// Остановка
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnAllStop_Click ( object sender, RoutedEventArgs e )
        {
            ver.RemoveAccountLicense(mainWindow, "RM");

            for ( int i = 0; i < mainWindow._dataProvider.RMItems.Count; i++ )
            {
                if ( mainWindow._dataProvider.RMItems [ i ].Check == true )
                {
                    mainWindow._dataProvider.RMItems [ i ].isRun = false;
                }
            }
            DtgdRm.ItemsSource = mainWindow._dataProvider.RMItems;
        }

        /// <summary>
        /// Запуск на выполнение
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnAllStart_Click ( object sender, RoutedEventArgs e )
        {
            
            #region Проверка есть ли позиции
            if ( new DialogOkCancel( "Возможно будет закрыта часть ваших позиций и снята часть заявок", "Внимание" ).Result == MessageBoxResult.OK )
            {
            }
            else
                return;
            #endregion
            try
            {
                if (ver.CountAccountLicense(mainWindow, "RM") == false)
                {
                    new DialogOkCancel("Количество запускаемых счетов больше, чем приобретено лицензий. Одна лицензия - один счет ММВБ и один счет ФОРТС", "Предупреждение");
                    return;
                }
            }
            catch
            { 
            
            }

            for ( int i = 0; i < mainWindow._dataProvider.RMItems.Count; i++ )
            {
                if ( mainWindow._dataProvider.RMItems [ i ].Check == true )
                {
                    if ( mainWindow._dataProvider.RMItems [ i ].isRun == false )
                    {
                        //if ( mainWindow._dataProvider.RMItems [ i ].Stage <= 0 )
                        //    mainWindow._dataProvider.RMItems [ i ].Stage = 1;

                        //if ( mainWindow._dataProvider.RMItems [ i ].DrowDown <= 0 )
                        //    mainWindow._dataProvider.RMItems [ i ].Stage = 1;

                        if ( mainWindow._dataProvider.RMItems [ i ].DrowDown < 1 )
                            mainWindow._dataProvider.RMItems [ i ].DrowDown = 1;

                        if ( mainWindow._dataProvider.RMItems [ i ].Account == cfg.Unknown ||
                            mainWindow._dataProvider.RMItems [ i ].ClientCode == cfg.Unknown ||
                            mainWindow._dataProvider.RMItems [ i ].TypeCalcutation == cfg.Unknown ||
                            mainWindow._dataProvider.RMItems [ i ].Variable == cfg.Unknown )
                        {
                            new DialogOkCancel( "Выберите счет, режим расчета убытком и тип расчета убытков", "Ошибка" );
                            return;
                        }

                        mainWindow._dataProvider.RMItems [ i ].isRun = true;
                        var list = mainWindow._dataProvider.ACLimiteItems.
                            Where
                            ( a =>
                                a.Account == mainWindow._dataProvider.RMItems [ i ].Account &&
                                a.ClientCode == mainWindow._dataProvider.RMItems [ i ].ClientCode
                            ).ToList( );
                        for ( int row = 0; row < list.Count; row++ )
                        {
                            if (mainWindow._dataProvider.RMItems[i].TypeEnterLimite == "Трейлинг профит")
                            {
                            list [ row ].FullPersent = 0;
                            list [ row ].Full = 0;
                            list[row].Deposite = list[row].CurrentBalance;
                            }
                        }
                    }
                }
            }

            DtgdRm.ItemsSource = mainWindow._dataProvider.RMItems;
        }

        private void RiskManLayout_Loaded ( object sender, RoutedEventArgs e )
        {

            this.Update( );

            _dsTimer.Interval = TimeSpan.FromMilliseconds( 2000 );
            _dsTimer.Start( );
            _dsTimer.Tick += new EventHandler( _dsTimer_Tick );

        }

        private void BtnBlocking_Click ( object sender, RoutedEventArgs e )
        {
            foreach ( var tmp in mainWindow._dataProvider.RMItems )
            {
                if ( tmp.Check == true )
                {
                    if ( tmp.IsBlock == true )
                        tmp.IsBlock = false;
                    else
                        tmp.IsBlock = true;
                }
            }
        }
    }
}